import React, {
  useState, Fragment, useEffect, useMemo,
} from 'react';
import { observer } from 'mobx-react-lite';
import { Spin } from 'choerodon-ui';
import { Choerodon } from '@choerodon/master';
import { Modal } from 'choerodon-ui/pro';
import YamlEditor from '../../../../../../../components/yamlEditor';
import InterceptMask from '../../../../../../../components/intercept-mask';
import ValuesModel from './open-model/ValuesModel';
import { handlePromptError } from '../../../../../../../utils';

import './index.less';

const valueKey = Modal.key();
const ValueModalContent = observer((
  {
    modal,
    store,
    valueDs,
    formatMessage,
    intlPrefix,
    prefixCls,
    vo,
    refresh,
    isMarket,
    isMiddleware,
    detailsStore,
  },
) => {
  const [value, setValue] = useState('');
  const [isDisabled, setIsDisabled] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const { yaml, name } = store.getUpgradeValue;
  const modalStyle = useMemo(() => ({
    width: '540px',
  }), []);
  // 增加文本内容不变时，部署按钮为禁用状态
  useEffect(() => {
    modal.update({
      okProps: {
        disabled: !value,
      },
    });
  }, [value]);
  modal.handleOk(handleOk);
  // 增加values副本数量不一致时的模态框
  // eslint-disable-next-line consistent-return
  async function handleOk() {
    await Modal.open({
      key: valueKey,
      title: formatMessage({ id: `${intlPrefix}.modal.values.value` }),
      movable: false,
      style: modalStyle,
      children: <ValuesModel valueDs={valueDs} count={store.getCount} />,
      // eslint-disable-next-line consistent-return
      async onOk() {
        if (isDisabled) return false;
        setIsLoading(true);
        const {
          id, parentId, projectId, appServiceVersionId, appServiceId,
        } = vo;
        const [envId] = parentId.split('**');
        const data = {
          values: value || yaml || '',
          instanceId: id,
          type: 'update',
          environmentId: envId,
        };
        if (isMarket || isMiddleware) {
          data.marketAppServiceId = appServiceId;
          data.marketDeployObjectId = appServiceVersionId;
        } else {
          data.appServiceId = appServiceId;
          data.appServiceVersionId = appServiceVersionId;
        }
        try {
          const values = valueDs.current.get('replicasStrategy');
          data.replicasStrategy = values;
          const result = await store.upgrade(projectId, data, isMarket, isMiddleware);
          if (handlePromptError(result)) {
            Choerodon.prompt('修改成功.');
            refresh && refresh();
          } else {
            Choerodon.prompt('修改失败.');
          }
        } catch (e) {
          Choerodon.handleResponseError(e);
        }
      },
    });
  }

  function toggleOkDisabled(flag) {
    modal.update({ okProps: { disabled: flag } });
  }

  function handleChange(nextValue) {
    setValue(nextValue);
  }

  function handleEnableNext(flag) {
    setIsDisabled(flag);
    toggleOkDisabled(flag);
  }

  return (
    <>
      <div className={`${prefixCls}-instance-upgrade-tips`}>
        <strong> 注意！若您修改了下方的Values，需要重新确认此次生效的「副本数量」策略：</strong>
        <span>
          <br />
          - 策略1：根据下方Values来设置「副本数量」。
          <br />
          - 策略2：与Pod详情界面中的「副本数量」保持一致，Values中控制「副本数量」的配置将不会生效。
          <br />
        </span>
      </div>
      <Spin spinning={store.getValueLoading}>
        <YamlEditor
          readOnly={false}
          value={value || yaml || ''}
          originValue={yaml}
          // eslint-disable-next-line react/jsx-no-bind
          onValueChange={handleChange}
          // eslint-disable-next-line react/jsx-no-bind
          handleEnableNext={handleEnableNext}
        />
      </Spin>
      <InterceptMask visible={isLoading} />
    </>
  );
});

export default ValueModalContent;
